﻿Imports System.ComponentModel
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.Web
Imports System.Drawing

Namespace Controls
    ''' <summary> 
    ''' 上传图片控件 
    ''' </summary> 
    <ToolboxItem(True), DefaultProperty("UpFilePath"), ToolboxData("<{0}:UpFile runat=server></{0}:UpFile>")> _
    Public Class UpFile
        Inherits WebControl
        ''' <summary> 
        ''' TextBox 控件变量 
        ''' </summary> 
        Protected tb As New System.Web.UI.WebControls.TextBox()

        ''' <summary> 
        ''' Label 控件变量 
        ''' </summary> 
        Protected Msglabel As System.Web.UI.WebControls.Label = New Label()

        ''' <summary> 
        ''' Button 控件变量 
        ''' </summary> 
        Protected UploadButton As New System.Web.UI.WebControls.Button()

        ''' <summary> 
        ''' FileUpload控件变量 
        ''' </summary> 
        Protected FileUpload As System.Web.UI.HtmlControls.HtmlInputFile = New HtmlInputFile()

        ''' <summary> 
        ''' 构造函数 
        ''' </summary> 
        Public Sub New()
            FileUpload.Size = 32
            Me.Controls.Add(FileUpload)

            UploadButton.Text = "上传"
            Me.Controls.Add(UploadButton)
            Me.Controls.Add(Msglabel)

            FileUpload.Attributes.Add("onfocus", "this.className='colorfocus';")
            FileUpload.Attributes.Add("onblur", "this.className='colorblur';")
            FileUpload.Attributes.Add("Class", "colorblur")

            tb.TextMode = System.Web.UI.WebControls.TextBoxMode.MultiLine
            tb.Width = 285
            tb.Attributes.Add("onfocus", "this.className='colorfocus';")
            tb.Attributes.Add("onblur", "this.className='colorblur';")
            tb.Attributes.Add("rows", "2")
            tb.Attributes.Add("cols", "53")
            tb.CssClass = "colorblur"
            Me.Controls.Add(tb)

            Me.Width = 350
            Me.Height = 30
            Me.BorderStyle = WebControls.BorderStyle.Dotted
            Me.BorderWidth = 0


            AddHandler UploadButton.Click, AddressOf UpFile_Click
        End Sub

        ''' <summary> 
        ''' 文件内容属性 
        ''' </summary> 
        <Bindable(True), Category("Appearance"), DefaultValue("")> _
        Public Property Text() As String
            Get
                Return Me.tb.Text
            End Get

            Set(ByVal value As String)
                Me.tb.Text = value
            End Set
        End Property

        Private m_waterMarkText As String = Nothing
        ''' <summary> 
        ''' 进行水印所使用的文字 
        ''' </summary> 
        <Bindable(True), Category("Appearance"), DefaultValue("算神工作室")> _
        Public Property WaterMarkText() As String
            Get
                Return m_waterMarkText
            End Get

            Set(ByVal value As String)
                m_waterMarkText = value
            End Set
        End Property

        ''' <summary> 
        ''' 要上传的文件路径 
        ''' </summary> 
        <Bindable(True), Category("Appearance"), DefaultValue("")> _
        Public Property UpFilePath() As String
            Get
                Dim o As Object = ViewState("RequiredFieldType")
                Return IIf((o Is Nothing), "", o.ToString())
            End Get
            Set(ByVal value As String)
                ViewState("RequiredFieldType") = value
            End Set
        End Property

        ''' <summary> 
        ''' 上传后所记入数据库时所引用的路径 
        ''' </summary> 
        <Bindable(True), Category("Appearance"), DefaultValue("")> _
        Public Property HttpPath() As String
            Get
                Dim o As Object = ViewState("HttpPath")
                Return IIf((o Is Nothing), "", o.ToString())
            End Get
            Set(ByVal value As String)
                ViewState("HttpPath") = value
            End Set
        End Property

        ''' <summary> 
        ''' 要上传的文件的类型，如：.gif , .jpg 
        ''' </summary> 
        <Bindable(True), Category("Appearance"), DefaultValue("jpg,gif,")> _
        Public Property FileType() As String
            Get
                Dim o As Object = ViewState("FileType")
                Return IIf((o Is Nothing), "", o.ToString())
            End Get
            Set(ByVal value As String)
                ViewState("FileType") = value
            End Set
        End Property


        ''' <summary> 
        ''' 是否生成缩略图 
        ''' </summary> 
        <Bindable(False), Category("Behavior"), DefaultValue("不生成缩略图"), TypeConverter(GetType(ThumbnailImageConverter)), Description("要滚动的对象。")> _
        Public Property ThumbnailImage() As String
            Get
                Dim o As Object = ViewState("ThumbnailImage")
                Return IIf((o Is Nothing), "", o.ToString())
            End Get
            Set(ByVal value As String)
                ViewState("ThumbnailImage") = value
            End Set
        End Property

        ''' <summary> 
        ''' 是否显示上传的文本框 
        ''' </summary> 
        <Bindable(True), Category("Appearance"), DefaultValue("true")> _
        Public Property IsShowTextArea() As Boolean
            Get
                Dim o As Object = ViewState("IsShowTextArea")

                Dim result As Boolean
                If o Is Nothing Then
                    result = True
                Else
                    If o.ToString() = "True" Then
                        result = True
                    Else
                        result = False
                    End If
                End If
                Return result
            End Get
            Set(ByVal value As Boolean)
                ViewState("IsShowTextArea") = value
                tb.Visible = value
                UploadButton.Visible = value
            End Set
        End Property

        ''' <summary> 
        ''' 输出html,在浏览器中显示控件 
        ''' </summary> 
        ''' <param name="output"> 要写出到的 HTML 编写器 </param> 
        Protected Overloads Overrides Sub Render(ByVal output As HtmlTextWriter)
            'output.Write(Text); 
            'RenderChildren(output); 
            CreateChildControls()

            If Me.HintInfo <> "" Then
                output.WriteBeginTag("span id=""" + Me.ClientID + """ onmouseover=""showhintinfo(this," + Me.HintLeftOffSet + "," + Me.HintTopOffSet + ",'" + Me.HintTitle + "','" + Me.HintInfo + "','" + Me.HintHeight + "','" + Me.HintShowType + "');"" onmouseout=""hidehintinfo();"">")
            End If

            MyBase.Render(output)

            If Me.HintInfo <> "" Then
                output.WriteEndTag("span")
            End If
        End Sub

        ''' <summary> 
        ''' 创建子控件 
        ''' </summary> 
        Protected Overloads Overrides Sub CreateChildControls()
            AddHandler UploadButton.Click, AddressOf UpFile_Click
        End Sub

        ''' <summary> 
        ''' 上传 
        ''' </summary> 
        ''' <returns></returns> 
        Public Function UpdateFile() As String
            Dim sSavePath As String = UpFilePath
            If FileUpload.PostedFile IsNot Nothing Then
                Dim myFile As HttpPostedFile = FileUpload.PostedFile
                Dim nFileLen As Integer = myFile.ContentLength
                If nFileLen = 0 Then
                    Msglabel.Text = "<br /><font color=red>没有选定被上传的文件</font></b>"
                    Return ""
                End If

                If FileType.IndexOf(System.IO.Path.GetExtension(myFile.FileName).ToLower()) < 0 Then
                    Msglabel.Text = "<br /><font color=red>文件必须是以" + FileType.Replace("|", " , ") + "为扩展名的文件</font></b>"
                    Return ""
                End If

                Dim myData As Byte() = New Byte(nFileLen - 1) {}
                myFile.InputStream.Read(myData, 0, nFileLen)

                Dim filenamedate As DateTime = DateTime.Now
                Dim sFilename As String = filenamedate.ToString("yyyy-MM-dd") + "_" + filenamedate.Hour.ToString() + "-" + filenamedate.Minute.ToString() + "-" + filenamedate.Second.ToString() + System.IO.Path.GetExtension(myFile.FileName).ToLower()
                Dim file_append As Integer = 0
                While System.IO.File.Exists(sSavePath + sFilename)
                    file_append += 1
                    sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + System.IO.Path.GetExtension(myFile.FileName).ToLower()
                End While


                '上传图片文件jpg,gif 
                If (System.IO.Path.GetExtension(myFile.FileName).ToLower() = ".jpg") OrElse (System.IO.Path.GetExtension(myFile.FileName).ToLower() = ".gif") Then
                    Dim myBitmap As Bitmap
                    Try
                        Dim newFile As New System.IO.FileStream(sSavePath + sFilename, System.IO.FileMode.Create)
                        newFile.Write(myData, 0, myData.Length)
                        newFile.Close()

                        myBitmap = New Bitmap(sSavePath + sFilename)

                        file_append = 0
                        Text = HttpPath + sFilename

                        If ThumbnailImage = "生成缩略图" Then
                            Dim width As Integer = myBitmap.Width / 3
                            Dim height As Integer = myBitmap.Height / 3
                            Dim sFileThumname As String = filenamedate.ToShortDateString() + "_" + filenamedate.Hour.ToString() + "-" + filenamedate.Minute.ToString() + "-" + filenamedate.Second.ToString() + "thum" + System.IO.Path.GetExtension(myFile.FileName).ToLower()

                            GetThumbnailImage(width, height, width / 2 - 60, height - 20, sSavePath + sFilename, sSavePath + sFileThumname)
                        End If

                        myBitmap.Dispose()
                        Msglabel.Text = "上传成功！"
                        Return Text
                    Catch errArgument As ArgumentException


                        'System.IO.File.Delete(sSavePath + sFilename); 
                        'return ""; 
                        Msglabel.Text = errArgument.ToString()
                    End Try
                Else
                    '上传除图片文件以外的全部文件 
                    myFile.SaveAs(sSavePath + sFilename)

                    Try
                        Text = HttpPath + sFilename
                        Return Text
                    Catch errArgument As ArgumentException
                        Msglabel.Text = errArgument.ToString()
                        System.IO.File.Delete(sSavePath + sFilename)
                        Return ""

                    End Try
                End If
            End If
            Return ""
        End Function

        ''' <summary> 
        ''' 上传单击事件 
        ''' </summary> 
        ''' <param name="sender"></param> 
        ''' <param name="e"></param> 
        Private Sub UpFile_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            UpdateFile()
        End Sub


        ''' <summary> 
        ''' 生成缩略图函数 
        ''' </summary> 
        ''' <param name="width">原始图片的宽度</param> 
        ''' <param name="height">原始图片的高度</param> 
        ''' <param name="left">水印字符的生成位置</param> 
        ''' <param name="right">水印字符的生成位置</param> 
        ''' <param name="picpath">原图的所在路径</param> 
        ''' <param name="picthumpath">生成缩略图的所在路径</param> 
        Public Sub GetThumbnailImage(ByVal width As Integer, ByVal height As Integer, ByVal left As Integer, ByVal right As Integer, ByVal picpath As String, ByVal picthumpath As String)
            Dim newfile As String = picthumpath
            Dim oldimage As System.Drawing.Image = System.Drawing.Image.FromFile(picpath)
            Dim thumbnailImage As System.Drawing.Image = oldimage.GetThumbnailImage(width, height, New System.Drawing.Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback), IntPtr.Zero)
            'Response.Clear(); 
            Dim output As New Bitmap(thumbnailImage)
            Dim g As Graphics = Graphics.FromImage(output)

            If (WaterMarkText Is Nothing) OrElse (WaterMarkText = "") Then
                g.DrawString(Nothing, New Font("Courier New", 14), New SolidBrush(Color.White), left, right)
            Else
                g.DrawString(WaterMarkText, New Font("Courier New", 14), New SolidBrush(Color.Blue), left, right)
            End If
            '写入文字到图片中 
            output.Save(picthumpath, System.Drawing.Imaging.ImageFormat.Jpeg)
            output.Dispose()
            'Response.ContentType = "image/gif"; 
        End Sub


        Public Function ThumbnailCallback() As Boolean
            Return True
        End Function

    End Class
End Namespace